package com.future;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description: 599. 两个列表的最小索引总和
 * <p>
 * 输入:list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"]，list2 = ["KFC", "Shogun", "Burger King"]
 * 输出: ["Shogun"]
 * 解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”，它有最小的索引和1(0+1)。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/minimum-index-sum-of-two-lists
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @author weiruibai.vendor
 * Date: 2023/3/14 14:46
 */
public class Solution_599 {

    private static Solution_599 instance = new Solution_599();

    public static void main(String[] args) {
        String[] list1 = new String[]{"Shogun", "Tapioca Express", "Burger King", "KFC"};
        String[] list2 = new String[]{"KFC", "Shogun", "Burger King"};
        String[] restaurant = instance.findRestaurant(list1, list2);
        System.out.println();
    }


    /**
     * 最小下标和
     *
     * @param list1
     * @param list2
     * @return
     */
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> m1 = new HashMap<>();
        int index = 0;
        for (String str : list1) {
            m1.put(str, index++);
        }
        List<String> ans = new ArrayList<>();
        int minIndexSum = Integer.MAX_VALUE;
        for (int i = 0; i < list2.length; i++) {
            String str = list2[i];
            if (m1.keySet().contains(str)) {
                int tmpSum = i + m1.get(str);
                if (minIndexSum > tmpSum) {
                    minIndexSum = tmpSum;
                    ans.clear();
                    ans.add(str);
                } else if (minIndexSum == tmpSum) {
                    ans.add(str);
                }
            }
        }
        return ans.toArray(new String[ans.size()]);
    }


}
